import 'dart:convert';
import 'dart:io';

import 'package:after_sale_plugin/package_event.dart';
import 'package:after_sale_plugin/pages/common/asset_model.dart';
import 'package:after_sale_plugin/pages/models/order_model.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_after_sale.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/main/controller.dart';
import 'package:inmotion_pro/pages/main/helper.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:inmotion_pro/service/permission_service.dart';
import 'package:inmotion_pro/service/translation_service.dart';
import 'package:inmotion_pro/utils/aliyun_oss_util.dart';
import 'package:inmotion_pro/utils/image_util.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'user_info/mixin.dart';
import 'package:after_sale_plugin/package_bridge.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class AfterPluginHelper with UserBasicInformationMixin {
  // 进入插件
  static toNamedPlugin(
    AfterSalePluginRouteEnum routeEnum, {
    String? orderNumber,
    VoidCallback? onRefreshWorkerTicketCallback,
  }) {
    final context = Get.context!;
    Get.toNamed(
      AfterSalePluginBridge.to.routeTo(
        routeEnum,
        (p0, p1, p2) async {
          switch (p0) {
            case AfterSalePluginActionEnum.showToast:
              Loading.showToast(p1);
              break;
            case AfterSalePluginActionEnum.dismissLoading:
              Loading.dismiss();
              break;
            case AfterSalePluginActionEnum.showConfirmAlert:
              Map<String, dynamic> plugin = p1 as Map<String, dynamic>;
              // 'content': '', 'confirm_title': '', 'cancel_title': '', 'show_cancel': '',
              LxAlert.show(plugin['content'],
                  confirmTitle: plugin['confirm_title'],
                  cancelTitle: plugin['cancel_title'],
                  showCancel: plugin['show_cancel'],
                  confirmCallback: (_) => p2(true),
                  cancelCallback: () => p2(false));
              break;
            case AfterSalePluginActionEnum.showLoading:
              Loading.showLoading(null);
              break;
            case AfterSalePluginActionEnum.checkError:
              _checkErrorInfo(p2);
              break;
            case AfterSalePluginActionEnum.connectVehicle:
              Loading.showLoading(local.connecting);
              debugPrint("需要连接的车辆 sn: $p1");
              // 首页车辆控制器
              VehicleController vehicleController =
                  Get.find(tag: AppRoutes.VEHICLE);
              // 因为在_selectVehicle这里已经选择过车辆了，所以这里直接刷新数据即可
              vehicleController.refreshData();
              vehicleController.state.bluetoothConnectState.listen((p0) {
                if (p0 == CustomBluetoothConnectState.connected) {
                  p2(jsonEncode(
                    {
                      'vehicle_data': {
                        'name':
                            GlobalService.to.currentVehicleModel.value.nickname,
                        'sn': GlobalService.to.currentVehicleModel.value.sn,
                        'connect_status': true,
                      },
                    },
                  ));
                }
              });
              break;
            case AfterSalePluginActionEnum.getCountryCode:
              _getCountryCode(p2);
              break;
            case AfterSalePluginActionEnum.selectAsssets:
              int maxCount = p1;
              _selectAssets(context, maxCount, p2);
              break;
            case AfterSalePluginActionEnum.uploadAsssets:
              _uploadAssets(p1, p2);
              break;
            case AfterSalePluginActionEnum.selectVehicle:
              _selectVehicle(p2);
              break;
            case AfterSalePluginActionEnum.newOrder:
              _newOrder(p1, p2);
              break;
            case AfterSalePluginActionEnum.updateOrder:
              _updateOrder(p1, p2);
              break;
            case AfterSalePluginActionEnum.orderDetail:
              _getOrderDetail(p1, p2);
              break;
            case AfterSalePluginActionEnum.orderList:
              _getOrderList(p1, p2);
              break;
            case AfterSalePluginActionEnum.orderResolved:
              _orderResolved(p1, p2);
              break;
            case AfterSalePluginActionEnum.orderUnsolved:
              _orderUnsolved(p1, p2);
              break;
            case AfterSalePluginActionEnum.getProductManual:
              int type = p1 as int;
              _getProductManual(type, p2);
              break;
            case AfterSalePluginActionEnum.getVideoGuide:
              int type = p1 as int;
              _getVideoGuide(type, p2);
              break;
            case AfterSalePluginActionEnum.playVideo:
              break;
            case AfterSalePluginActionEnum.playPicture:
              break;
            case AfterSalePluginActionEnum.getRegion:
              p2(GlobalService.to.isChinaRegion.value);
              break;
            default:
              break;
          }
          // 刷新最新的工单状态
          if (onRefreshWorkerTicketCallback != null) {
            onRefreshWorkerTicketCallback();
          }
        },
        arguments: {
          'accept_language':
              TranslationService.getLocale().toLanguageTag().contains("zh-")
                  ? 0
                  : 1,
          'vehicle_data': {
            'name': GlobalService.to.currentVehicleModel.value.nickname,
            'sn': GlobalService.to.currentVehicleModel.value.sn,
            'connect_status': VechileConnectionService.to.bluetoothConnectState.value ==
                CustomBluetoothConnectState.connected,
          },
          'is_manual': routeEnum == AfterSalePluginRouteEnum.productManual,
          'order_number': orderNumber,
        },
      ),
    );
  }

  // 检测故障信息
  static _checkErrorInfo(Function(dynamic) callBack) {
    Get.toNamed(AppRoutes.VEHICLE_ERROR, arguments: true)?.then((rsp) {
      callBack(rsp);
    });
  }

  // 获取国家code
  static _getCountryCode(Function(dynamic) callBack) {
    Loading.showLoading(null);
    ApiHelper().getCountryList().then((rsp) {
      callBack(rsp.map((e) => e.countryCode.toString()).toList());
    }).catchErrorHandler();
  }

  // 选择车型
  static _selectVehicle(Function(dynamic) callBack) {
    MainHelper().switchVehicle(
      isSimpleVersion: true,
      disconnectAndSearchCallback: () {},
      changeVehicleCallback: (model) {
        // 因为断开蓝牙时，需要耗时，给个延时，确保蓝牙断开完成
        Future.delayed(const Duration(milliseconds: 500), () {
          callBack({
            'name': model.nickname,
            'sn': model.sn,
            'connect_status': VechileConnectionService.to.bluetoothConnectState.value ==
                    CustomBluetoothConnectState.connected &&
                GlobalService.to.currentVehicleModel.value.sn == model.sn,
          });
        });
      },
    );
  }

  // 选择图片/视频
  static Future<void> _selectAssets(
      BuildContext context, int maxCount, Function(dynamic) callBack) async {
    selectPhotos() {
      AssetPickerConfig config = const AssetPickerConfig();
      // 当选中了图片后，再次选择时，只能选择图片（图片、视频不能共存）
      debugPrint("uploadAssets");
      config = AssetPickerConfig(
        maxAssets: maxCount,
        gridCount: 4,
        specialPickerType: SpecialPickerType.wechatMoment,
        textDelegate:
            assetPickerTextDelegateFromLocale(TranslationService.getLocale()),
      );

      AssetPicker.pickAssets(
        context,
        pickerConfig: config,
      ).then((result) async {
        if (result != null && result.isNotEmpty) {
          final assets = Set<AssetEntity>.from(result);
          for (var asset in assets) {
            AssetModel model = AssetModel.fromMap({});
            model.id = asset.id;
            model.type = asset.type;
            File? file = await asset.file;
            if (file != null) {
              model.filePath = file.path;
              model.size = ImageUtil.getSize(file.path);
              const int maxSize = 100 * 1024 * 1024; // 100MB
              int fileSize = await file.length();
              if (fileSize > maxSize) {
                Loading.showToast("file_size_exceeds_limit_100MB".tr);
                return;
              } else {
                switch (asset.type) {
                  case AssetType.video:
                    String? thumbPath =
                        await ImageUtil.thumbnailVideoFile(file.path);
                    if (thumbPath != null) {
                      model.thumbFilePath = thumbPath;
                    }
                    break;
                  default:
                    model.thumbFilePath = file.path;
                    break;
                }
                callBack(jsonEncode(model.toMap()));
              }
            }
          }
        }
      });
    }

    PermissionService.to.requestPhotoPermission((success) {
      if (success) {
        selectPhotos();
      } else {
        Loading.showToast(local.cancel);
      }
    });
  }

  // 上传图片/视频
  static Future<void> _uploadAssets(
      String filePath, Function(dynamic) callBack) async {
    await AliyunOSSUtil()
        .uploadFile(FileDirectory.afterSale, File(filePath))
        .then((value) => callBack(value));
  }

  // 获取产品手册
  static _getProductManual(int type, Function(dynamic) callBack) {
    Loading.showLoading(null);
    ApiHelper().getProductManualData(type).then((rsp) {
      Loading.dismiss();
      callBack(rsp);
    }).catchErrorHandler();
  }

  // 获取视频指南
  static _getVideoGuide(int type, Function(dynamic) callBack) {
    Loading.showLoading(null);
    ApiHelper().getVideoGuideData(type).then((rsp) {
      Loading.dismiss();
      callBack(rsp);
    }).catchErrorHandler();
  }

  // 新增工单
  static _newOrder(String orderInfo, Function(dynamic) callBack) {
    ReportOrderInfo newOrderInfo =
        ReportOrderInfo.fromMap(jsonDecode(orderInfo));
    List<String> srcList = newOrderInfo.assetModels
        .map((element) => element.src)
        .toList()
        .where((p0) => p0.isNotEmpty)
        .toList();
    Loading.showLoading(null);
    Map<String, dynamic>? diagnosis = newOrderInfo.diagnosis.value.toMap();
    ApiHelper()
        .createWorkOrder(
            newOrderInfo.sn,
            newOrderInfo.reportPersonName.value,
            newOrderInfo.reportPhoneNumber.value,
            newOrderInfo.reportType.value,
            newOrderInfo.problemContent.value,
            srcList,
            diagnosis)
        .then((rsp) {
      Loading.dismiss();
      callBack(rsp);
    }).catchErrorHandler();
  }

  // 修改工单
  static _updateOrder(String orderInfo, Function(dynamic) callBack) {
    ReportOrderInfo oldOrderInfo =
        ReportOrderInfo.fromMap(jsonDecode(orderInfo));
    List<String> srcList = oldOrderInfo.feedback.first.attachment
        .where((p0) => p0.isNotEmpty)
        .toList();
    Loading.showLoading(null);
    ApiHelper()
        .updateWorkOrder(
      oldOrderInfo.id,
      srcList,
      feedbackContent: oldOrderInfo.supplementContent,
    )
        .then((isSuccess) {
      Loading.dismiss();
      callBack(isSuccess);
    }).catchErrorHandler();
  }

  // 工单详情
  static _getOrderDetail(String id, Function(dynamic) callBack) {
    Loading.showLoading(null);
    ApiHelper().getWorkOrderDetail(id).then((rsp) {
      Loading.dismiss();
      callBack(rsp);
    }).catchErrorHandler();
  }

  // 工单列表
  static _getOrderList(
      bool hidenLoading, Function(Map<String, dynamic>) callBack) {
    if (!hidenLoading) {
      Loading.showLoading(null);
    }
    ApiHelper().getWorkOrderList().then((rsp) {
      if (!hidenLoading) {
        Loading.dismiss();
      }
      callBack(rsp);
    }).catchErrorHandler();
  }

  // 工单已解决
  static _orderResolved(String id, Function(dynamic) callBack) {
    Loading.showLoading(null);
    ApiHelper().markWorkOrderSolved(id).then((isSuccess) {
      Loading.dismiss();
      callBack(isSuccess);
    }).catchErrorHandler();
  }

  // 工单未解决
  static _orderUnsolved(String orderInfo, Function(dynamic) callBack) {
    ReportOrderInfo oldOrderInfo =
        ReportOrderInfo.fromMap(jsonDecode(orderInfo));
    List<String> srcList = oldOrderInfo.resolutionResult.value.attachment
        .where((p0) => p0.isNotEmpty)
        .toList();
    Loading.showLoading(null);
    ApiHelper()
        .markWorkOrderUnsolved(
      oldOrderInfo.id,
      oldOrderInfo.resolutionResult.value.comment.value,
      srcList,
    )
        .then((isSuccess) {
      Loading.dismiss();
      callBack(isSuccess);
    }).catchErrorHandler();
  }
}
